package cn.edu.zstu.qingzhu.qingzhushop.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author ShenTuZhiGang
 * @version 1.0.0
 * @date 2020-11-23 18:24
 */
public class HttpServletUtil {
    public static MediaType getRequestPrimaryAcceptMediaType(HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        MediaType acceptMediaType;
        if (StringUtils.isEmpty(accept)) {
            acceptMediaType = MediaType.APPLICATION_JSON;
        } else {
            String[] str = accept.split(",");
            if (str.length > 0) {
                try {
                    acceptMediaType = MediaType.valueOf(str[0]);
                } catch (InvalidMediaTypeException ex) {
                    acceptMediaType = MediaType.APPLICATION_JSON;
                }
            } else {
                acceptMediaType = MediaType.APPLICATION_JSON;
            }
        }
        return acceptMediaType;
    }

    public static void writeObjectToResponse(HttpServletResponse httpServletResponse, Object obj) throws IOException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        String s = new ObjectMapper().writeValueAsString(obj);
        out.write(s);
        out.flush();
        out.close();
    }
}
